/*
 * @Description: In User Settings Edit
 * @Author: your name
 * @Date: 2019-05-28 17:28:33
 * @LastEditTime: 2020-03-23 16:26:30
 * @LastEditors: Please set LastEditors
 */
(function(para) {
    document.cookie="bdgjnopass="+ new Date().getTime() +";path=/";
    var p = para.sdk_url, n = para.name, w = window, d = document, s = 'script',x = null,y = null;
    w['sensorsDataAnalytic201505'] = n;
    w[n] = w[n] || function(a) {return function() {(w[n]._q = w[n]._q || []).push([a, arguments]);}};
    var ifs = ['track','quick','register','registerPage','registerOnce','clearAllRegister','trackSignup', 'trackAbtest', 'setProfile','setOnceProfile','appendProfile', 'incrementProfile', 'deleteProfile', 'unsetProfile','identify','login','logout','trackLink'];
    for (var i = 0; i < ifs.length; i++) {
        w[n][ifs[i]] = w[n][ifs[i]] || w[n].call(null, ifs[i]);
    }
    if (!w[n]._t) {
        x = d.createElement(s), y = d.getElementsByTagName(s)[0];
        x.async = 1;
        x.src = p;
        w[n].para = para;
        y.parentNode.insertBefore(x, y);
    }
})({
    sdk_url: '/base/js/sensorsdata.min.js',
    name: 'sensors',
    //'https://xnjkfx.cpic.com.cn:8006/sa?project=SXBDGJ'
    //['https://xnjkfx.cpic.com.cn:8006/sa?project=SXBDGJ','https://xnjkfx.cpic.com.cn:8006/sa?project=SXGW']
    //['https://xnjkfxsit.cpic.com.cn/sa?project=SXBDGJ','https://xnjkfxsit.cpic.com.cn/sa?project=SXGW']
    //server_url:['https://xnjkfxsit.cpic.com.cn/sa?project=SXBDGJ','https://xnjkfxsit.cpic.com.cn/sa?project=SXGW'],
    // server_url:['https://xnjkfx.cpic.com.cn:8006/sa?project=SXBDGJ','https://xnjkfx.cpic.com.cn:8006/sa?project=SXGW'],
    server_url: location.href.match(/(http[s]?\:\/\/)(.*?)\//)[2] == 'bdgj-sit.cpic.com.cn' ? 'https://xnjkfxsit.cpic.com.cn/sa?project=SXGW' : 'https://xnjkfx.cpic.com.cn:8006/sa?project=SXGW',
    heatmap: {
        //是否开启点击图，default 表示开启，自动采集 $WebClick 事件，可以设置 'not_collect' 表示关闭。
        clickmap: 'default',
        get_vtrack_config: true,
        useCapture: true,
        //是否开启触达注意力图，not_collect 表示关闭，不会自动采集 $WebStay 事件，可以设置 'default' 表示开启。
        scroll_notice_map:'not_collect'
    }
});
sensors.registerPage({
	systemName:"寿险2014版移动服务应用系统",
	toolName:"保单管家"
});

/*
sensors.quick('autoTrack');
if(sessionStorage.getItem('entryOpenid'))
    sensors.login(sessionStorage.getItem('entryOpenid'))
*/
if(sessionStorage.getItem('entryOpenid')){
    sensors.login(sessionStorage.getItem('entryOpenid'));
    sensors.quick('isReady',function(){
        sensors.quick('autoTrack');
    });
};


//公共自定义埋点方法
function MDclick(pagename,custid,custno,custname,modno,sessionid,bqtype,policyno,faceocr,cardocr,clickName){
	//自定义埋点-star
    sensors.track('bdgj_visit', {
		pageName:pagename,
		openid:sessionStorage.getItem('entryOpenid'),
		custId:custid,
		custNo:custno,
		custName:custname,
        modno: modno,
        sessionId: sessionid,
        bqType: bqtype,
        policyNo: policyno,
        faceOcr: faceocr,
        cardOcr: cardocr,
        ClickName: clickName
    });
    //自定义埋点-end
}

//我的门店埋点--@220617
function mystoreMDclick(pagename, idnum, ffid, custname, sessionid, province, city, modno, storeaddr, yytime, custaddr, branchname, buttonname, keyword) {
    //自定义埋点-star
    sensors.track('bdgj_click', {
        pageName: pagename,
        custId: idnum,
        custNo: ffid,
        custName: custname,
        sessionId: sessionid,
        bqType: "WDMD",
        province: province,//查询省
        city: city,//查询城市
        modno: modno,//批单号
        storeAddr: storeaddr,//预约门店地址
        yyTime: yytime,//预约时间
        custAddr: custaddr,//云柜面，分公司-客户地址
        branchName: branchname,//分公司名称
        buttonName: buttonname,//例：用户登录、弹框关闭按钮、即刻去体验、云柜面服务、联系保单管家、预约去柜面
        key_word: keyword//例：我要改个人信息-改手机号（3即刻去体验）
    });
    //自定义埋点-end
}

if (!Array.prototype.forEach) {
    Array.prototype.forEach = function forEach(callback, thisArg) {
        var T, k;
        if (this == null) {
            throw new TypeError("this is null or not defined");
        }
        var O = Object(this);
        var len = O.length >>> 0;
        if (typeof callback !== "function") {
            throw new TypeError(callback + " is not a function");
        }
        if (arguments.length > 1) {
            T = thisArg;
        }
        k = 0;
        while (k < len) {
            var kValue;
            if (k in O) {
                kValue = O[k];
                callback.call(T, kValue, k, O);
            }
            k++;
        }
    };
}

(function () {
    var browser = {};
    var userAgent = navigator.userAgent.toLowerCase();
    var s;
    (s = userAgent.match(/msie ([\d.]+)/)) ? browser.ie = s[1] : (s = userAgent.match(/firefox\/([\d.]+)/)) ? browser.firefox = s[1] : (s = userAgent.match(/chrome\/([\d.]+)/)) ? browser.chrome = s[1] : (s = userAgent.match(/opera.([\d.]+)/)) ? browser.opera = s[1] : (s = userAgent.match(/version\/([\d.]+).*safari/)) ? browser.safari = s[1] : 0;
    var version = "";
    if (browser.ie) {
        version = 'IE ' + browser.ie;
    }
    else {
        if (browser.firefox) {
            version = 'firefox ' + browser.firefox;
        }
        else {
            if (browser.chrome) {
                version = 'chrome ' + browser.chrome;
            }
            else {
                if (browser.opera) {
                    version = 'opera ' + browser.opera;
                }
                else {
                    if (browser.safari) {
                        version = 'safari ' + browser.safari;
                    }
                    else {
                        version = '未知浏览器';
                    }
                }
            }
        }
    }

})()


var htmlBq = document.documentElement;
function allSize() {
    var htmlWidth = document.documentElement.clientWidth || document.body.clientWidth;
    var htmlDom = document.getElementsByTagName('html')[0];
    htmlDom.style.fontSize = htmlWidth / 3.75 + 'px';
};

function isEmpty(str) {
    if (str == 'undefined' || !str || !/[^\s]/.test(str)) {
        return true;
    } else {
        return false;
    }
}

function showErr(id, content) {
    $("#"+id).addClass("leftword-error");
    $("#"+id).html(content);
}

function hideErr() {
    $(".line_grey").removeClass("leftword-error").html("")
}

function scrollToEnd(){//滚动到底部
    var h = $(document).height()-$(window).height();
    $(document).scrollTop(h);
}
window.onresize = function () {
    setTimeout(function(){
        allSize();
    },100);
};
allSize();

// (function () {
//     var ua = navigator.userAgent.toLowerCase();
//     var isWeixin = ua.indexOf('micromessenger') != -1;
//     if (!isWeixin) {
//         document.head.innerHTML =
//             '<title>抱歉，出错了</title><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=0"><link rel="stylesheet" type="text/css" href="https://res.wx.qq.com/open/libs/weui/0.4.1/weui.css">';
//         document.body.innerHTML =
//             '<div class="weui_msg"><div class="weui_icon_area"><i class="weui_icon_info weui_icon_msg"></i></div><div class="weui_text_area"><h4 class="weui_msg_title">请在微信客户端打开链接</h4></div></div>';
//     }
// })()




var base = base || {};
(function () {
    if (window.ie8StopFlag) return false
    var that = this,

        //通过grunt打包时会替换此值， 当此值为20240116022357才能正确匹配到并替换
        _time = "20240116022357",

        //等待执行的模块列表
        pendingModule = [],

        //当前文件名称
        coreFileName = "base.js",

        //requireJs文件名
        requireFileName = "require.js",

        mainAttrName = "ready-main",

        //ready-main
        readyMainSrc = "",

        readyState = "wait", //wait ready  

        //预加载模块
        perModule = [];



    /**
     * 当前项目根所在目录
     */
    this.moduleBaseUrl = function () {
        var srcUrl = "";
        [].forEach.call(document.getElementsByTagName("script"), function (dom) {
            if (dom.src.indexOf(coreFileName) > -1) {
                srcUrl = dom.src;//.match(new RegExp("(.*?)("+coreFileName+")","i"))[1];
                readyMainSrc = dom.getAttribute(mainAttrName);
                perModule = (dom.getAttribute("perModule") || "").split(",");
            }
        });
        return srcUrl.replace(/\/base\/.*$/, "");
    }();

    /**
     * 当前项目根所在目录
     */
    this.moduleUrl = function () {
        return that.moduleBaseUrl.replace(/http(s)?:\/\/.+?\//, window.location.protocol + "//" + window.location.host + "/");
    }();

    /**
     *  根据域名返回当前环境
     */
    this.environment = function () {
        var host = location.href.match(/(http[s]?\:\/\/)(.*?)\//),
            hostNames = {
                "bdgj.cpic.com.cn": "prod",
                "bdgj-sit.cpic.com.cn": "sit",
                "bdgj-uat.cpic.com.cn": "uat",
                "bdgj-dev.cpic.com.cn": "dev",
                "local.cpic.com.cn": "local",
                "localhost": "local",
                "localhost:8080": "local",
                "localhost:8091": "local",
            };

        host = host ? host[2] : "";

        return hostNames[host] || "sit";
    }();

    /**
     * Debug打印
     */
    this.opendebugPrint = function () {
        return false;//window.location.host!="ump.cpic.com.cn";
    }();

    this.logUl = null;

    this.log = function (msg) {
        if (that.opendebugPrint) {
            if ($("#cpic_logs").size() < 1) {
                var html = $('<div id="cpic_logs"><div class="log_content"><ul></ul></div><button type="button" class="btn btn-default log_close" onclick="$(this).parent().fadeOut();base.unLockBodyScroll()">关闭</div>');
                that.logUl = html.find("ul");
                $("body").append(html);
            }
            that.logUl.append("<li>" + new Date().Format("yyyy-MM-dd hh:mm:ss") + "<br/>" + msg + "</li>");

            if (window.console) {
                console.log(msg);
            }
        }
    };
    this.eventLog = function () {
        if (that.opendebugPrint) {
            this.log("页面首次加载完成");

            var clickCount = 0, setObj = false, time = 3000;
            $(".page-header .CAFE_CASE").click(function (e) {
                if (!setObj) {//
                    setObj = true;
                    setTimeout(function () {
                        setObj = false;
                        clickCount = 0;
                    }, time);
                }
                if (++clickCount >= 5) {
                    that.lockBodyScroll();
                    $('#cpic_logs').fadeIn();
                }
                e.preventDefault();
            });
        }
    };

    //锁定body滚动条
    this.lockBodyScroll = function () {
        //禁止页面滚动
        if (this.operatingSystem.container == "weixin") {
            // return;
        }
        this._lockBodyTop = $(window).scrollTop();
        $("body").css({
            position: "fixed",
            overflow: "hidden",
            height: this.win.height
            , 'top': this._lockBodyTop * -1
        });
    };

    //解除锁定body滚动条
    this.unLockBodyScroll = function () {
        if (this.operatingSystem.container == "weixin") {
            // return;
        }

        $("body").css({
            position: "",
            overflow: "",
            height: "",
            top: ""
        });

        document.documentElement.scrollTop = this._lockBodyTop;
        document.body.scrollTop = this._lockBodyTop;
    };

    // 判断当前环境
    this.operatingSystem = {
        clientOs: function () {
            var sUserAgent = navigator.userAgent;
            var isWin = (navigator.platform == "Win32") || (navigator.platform == "Windows");
            var isMac = (navigator.platform == "Mac68K") || (navigator.platform == "MacPPC") || (navigator.platform == "Macintosh") || (navigator.platform == "MacIntel");
            if (isMac) {
                return "Mac";
            }
            var isUnix = (navigator.platform == "X11") && !isWin && !isMac;
            if (isUnix) {
                return "Unix";
            }
            var isLinux = (String(navigator.platform).indexOf("Linux") > -1);
            if (isLinux) {
                return "Linux";
            }
            if (isWin) {
                var isWinXP = sUserAgent.indexOf("Windows NT 5.1") > -1 || sUserAgent.indexOf("Windows XP") > -1;
                if (isWinXP) {
                    return "WinXP";
                }
                var isWin7 = sUserAgent.indexOf("Windows NT 6.1") > -1 || sUserAgent.indexOf("Windows 7") > -1;
                if (isWin7) {
                    return "Win7";
                }
            }
            return "other";
        }(),
        browse: function () {
            var browser = {};
            var userAgent = navigator.userAgent.toLowerCase();
            var s;
            (s = userAgent.match(/msie ([\d.]+)/)) ? browser.ie = s[1] : (s = userAgent.match(/firefox\/([\d.]+)/)) ? browser.firefox = s[1] : (s = userAgent.match(/chrome\/([\d.]+)/)) ? browser.chrome = s[1] : (s = userAgent.match(/opera.([\d.]+)/)) ? browser.opera = s[1] : (s = userAgent.match(/version\/([\d.]+).*safari/)) ? browser.safari = s[1] : 0;
            var version = "";
            if (browser.ie) {
                version = 'IE ' + browser.ie;
            }
            else {
                if (browser.firefox) {
                    version = 'firefox ' + browser.firefox;
                }
                else {
                    if (browser.chrome) {
                        version = 'chrome ' + browser.chrome;
                    }
                    else {
                        if (browser.opera) {
                            version = 'opera ' + browser.opera;
                        }
                        else {
                            if (browser.safari) {
                                version = 'safari ' + browser.safari;
                            }
                            else {
                                // version = '未知浏览器'; // 电子保单下载如果传中文会报错
                                version = 'other';
                            }
                        }
                    }
                }
            }
            return version;
        }(),
        isWeiXin: function () {
            var ua = window.navigator.userAgent.toLowerCase();
            if(ua.match(/MicroMessenger/i) == 'micromessenger'){
                return true;
            }else{
                return false;
            }
        }(),
        container: function () {
            if (isWeiXin()) {
                return "weixin";
            } else if (isWeibo()) {
                return "weibo";
            } else {
                return "web";
            };

            //微信
            function isWeiXin() {
                var ua = window.navigator.userAgent.toLowerCase();

                if (/MicroMessenger/i.test(ua)) {
                    return true;
                } else {
                    return false;
                }
            };
            //微博
            function isWeibo() {
                var ua = navigator.userAgent;
                return (ua.indexOf("Weibo") > -1 && ua.indexOf("_weibo_") > -1);
            };
        }()
    };

    //less than equal to 小于等于ie9版本
    this.operatingSystem.IE9LTET = function () {
        if (that.operatingSystem.browse.indexOf("IE") >= 0) {
            return parseInt(base.operatingSystem.browse.match(/\d+/)[0]) <= 9;
        }
        return false;
    }();

    //less than equal to 小于等于ie8版本
    this.operatingSystem.IE8LTET = function () {
        if (that.operatingSystem.browse.indexOf("IE") >= 0) {
            return parseInt(base.operatingSystem.browse.match(/\d+/)[0]) <= 8;
        }
        return false;
    }();


    /**
     *  覆盖一级json对象
     */
    this.extend = function (des, src) {
        for (var i in src) {
            des[i] = src[i];
        }
        return des;
    };

    this.isArray = function (o) {
        return o != null && typeof o == "object" && 'splice' in o && 'join' in o;
    };

    this.isFunction = function (o) {
        return typeof o == "function";
    };

    this.isObject = function (o) {
        return typeof o == "object";
    };

    this.isString = function (o) {
        return typeof o == "string";
    };

    this.isBoolean = function (o) {
        return typeof o == "boolean";
    };

    this.isUndefined = function (o) {
        return typeof o == "undefined";
    };

    this.isNumber = function (o) {
        return typeof o == "number";
    };

    /** 动态加载js文件以及css文件
       * @param  {filename} 文件名 String or Array
       * @param  {charset}  文件编码
       * @param  {callback(code)} 文件加载完成回调函数 code[success,error]
       * @demo
              base.loadJsCssFile({
                  filename:'demo.js',
                  charset:'utf-8',
                  media:'',
                  callback:function(status){
                  },
                  attributes:[]
              });
      */
    this.loadJsCssFile = function (params) {
        var dp = {
            filename: null,//array in filename[{filename:'',media:'',charset:'',ftype:''}]
            charset: null,
            media: null,
            ftype: null,
            attributes: [],
            callback: function (code) { }
        }, _index = -1;

        this.extend(dp, params);

        function loadFile(filename, charset, media, callback, ftype, attributes) {
            var fileref, src = filename, filetype, checkFile = true;
            if (typeof filename == 'object') {
                charset = filename.charset || charset;
                media = filename.media || media;
                src = filename.filename;
                ftype = filename.ftype;
                attributes = filename.attributes || attributes;
                checkFile = typeof filename.checkFile == 'boolean' ? filename.checkFile : true;
            }
            filetype = src;

            if (!filetype) {
                that.isFunction(callback) && callback('success');
                return;
            }
            filetype = filetype.substring(filetype.lastIndexOf(".") + 1).toLowerCase();
            filetype = ftype || filetype;

            //createElement
            if (/^js/i.test(filetype)) {
                fileref = document.createElement('script');
                fileref.setAttribute("type", "text/javascript");
                fileref.setAttribute("src", src);
            } else if (/^css/i.test(filetype)) {
                fileref = document.createElement('link');
                fileref.setAttribute("rel", "stylesheet");
                fileref.setAttribute("type", "text/css");
                fileref.setAttribute("href", src);
            }
            else {//如果非此两种文件
                that.isFunction(callback) && callback('error');
            }

            //event and callback bind
            if (typeof fileref != "undefined") {
                charset && fileref.setAttribute("charset", charset);
                media && fileref.setAttribute("media", media);
                if (attributes && attributes.length) {
                    attributes.forEach(function (o) {
                        fileref.setAttribute(o.key, o.value);
                    });
                }
                if (filetype == "css")//css 的onload不兼容所有浏览器
                {
                    that.isFunction(callback) && callback('success');
                }
                else {
                    fileref.onload = fileref.onreadystatechange = function () {
                        if (!this.readyState ||
                            this.readyState == 'loaded' ||
                            this.readyState == 'complete') {
                            (!this.isRunCallback) && that.isFunction(callback) && callback('success');
                            this.isRunCallback = true;
                        }
                    }
                }
                fileref.onerror = function () {
                    that.isFunction(callback) && callback('error');
                };
                document.getElementsByTagName("head")[0].appendChild(fileref);
            }
        }
        if (this.isArray(dp.filename)) {
            (function _load(status) {
                if (status === "error") {
                    dp.callback('error');
                    return;
                }
                _index++;
                if (_index >= dp.filename.length) {
                    dp.callback('success');
                    return;
                }
                loadFile(dp.filename[_index], dp.charset, dp.media, _load, dp.ftype, dp.attributes);
            })();
        }
        else {
            loadFile(dp.filename, dp.charset, dp.media, dp.callback, dp.ftype, dp.attributes);
        }
    };

    if(this.environment != 'local'){
    	if(location.href.indexOf("/loan/")>-1 || location.href.indexOf("/myAccount/")>-1 || location.href.indexOf("/mypayment/")>-1 || location.href.indexOf("/tb/")>-1){//贷款、给付、账户提取加载eye
        	var eyeUrl = this.environment == 'prod'?"https://isee.cpic.com.cn/isee/eye":"https://isee-test-sit.cpic.com.cn/isee/eye";//众安回溯
        	this.loadJsCssFile({
                filename: eyeUrl + ".js?_t=" + _time,
                //attributes:[{ key:"data-main",value:"main" }],
                callback: function () {

                }.bind(this)
            });
        }
    }
    //加载require文件并在加载完成后运行所有等待执行的模块
    this.loadJsCssFile({
        filename: this.moduleBaseUrl + "/core/" + requireFileName + "?_t=" + _time,
        //attributes:[{ key:"data-main",value:"main" }],
        callback: function () {

            initRequireJs();

            readyMain();

            runAllPending();

        }.bind(this)
    });



    /**
     * setLocalStorage
     */
    this.setLocalStorage = function (key, value, isJson) {
        that.log("设置localStorage数据key=" + key + ",是否为json数据:" + (isJson ? "true" : "false"));
        if (window.localStorage) {
            if (isJson) {
                value = JSON.stringify(value);
            }
            window.localStorage[key] = value;
        } else {
            that.log("当前浏览器不支持localStorage");
        }
    };
    /**
     * getLocalStorage
     */
    this.getLocalStorage = function (key, isJson) {
        that.log("获取localStorage数据key=" + key + ",是否为json数据:" + (isJson ? "true" : "false"));
        if (window.localStorage) {
            var value = window.localStorage[key] || "";
            if (isJson && value) {
                value = JSON.parse(value);
            }
            that.log("获取localStorage数据key=" + key + ",value=" + value);
            return value;
        } else {
            that.log("当前浏览器不支持localStorage");
        }
    };
    /**
     * removeLocalStorage
     */
    this.removeLocalStorage = function (key) {
        that.log("移除localStorage数据key=" + key);
        if (window.localStorage) {
            window.localStorage.removeItem(key);
        } else {
            that.log("当前浏览器不支持localStorage");
        }
    };
    /**
     * setSessionStorage
     */
    this.setSessionStorage = function (key, value, isJson) {
        var _wkey = "sessionStorage";
        if (/mqqbrowser/i.test(window.navigator.userAgent)) {
            //qq手机浏览器不支持sessionStorage多页面共享
            _wkey = "localStorage";
        }
        that.log("设置sessionStorage数据key=" + key + ",是否为json数据:" + (isJson ? "true" : "false"));
        if (window[_wkey]) {
            if (isJson) {
                value = JSON.stringify(value);
            }
            that.log("设置sessionStorage数据key=" + key + ",value=" + value);
            window[_wkey][key] = value;
        } else {
            that.log("当前浏览器不支持sessionStorage");
        }
    };
    /**
     * getSessionStorage
     */
    this.getSessionStorage = function (key, isJson) {
        var _wkey = "sessionStorage";
        if (/mqqbrowser/i.test(window.navigator.userAgent)) {
            _wkey = "localStorage";
        }
        that.log("获取sessionStorage数据key=" + key + ",是否为json数据:" + (isJson ? "true" : "false"));
        if (window[_wkey]) {
            var value = window[_wkey][key] || "";
            if (isJson && value) {
                value = JSON.parse(value);
            }
            that.log("获取sessionStorage数据key=" + key + ",value=" + value);
            return value;
        } else {
            that.log("当前浏览器不支持sessionStorage");
        }
    };

    /**
     * removeSessionStorage
     */
    this.removeSessionStorage = function (key) {
        var _wkey = "sessionStorage";
        if (/mqqbrowser/i.test(window.navigator.userAgent)) {
            _wkey = "localStorage";
        }
        that.log("移除sessionStorage数据key=" + key);
        if (window[_wkey]) {
            window[_wkey].removeItem(key);
        } else {
            that.log("当前浏览器不支持sessionStorage");
        }
    };
    /**
     * getCookie
     */
    this.getCookie = function (key) {
        that.log("获取cookie值,当前域为" + document.domain + ",key为" + key);
        var arr, reg = new RegExp("(^| )" + key + "=([^;]*)(;|$)");
        arr = document.cookie.match(reg);
        if (arr) {
            that.log("获取cookie值,\r\nkey:" + key + "\r\nvalue:" + arr[2]);
            return unescape(arr[2]);
        } else {
            that.log("获取cookie值,不存在key为" + key + "的cookie");
            return null;
        }
    };
    /**
     * setCookie
     */
    this.setCookie = function (params) {
        params = params || {};
        //params=name, value,domain,expTime分钟
        that.log("设置cookie值,cookie_name为" + params.name);
        var exp = new Date();
        var expires = "";
        if (params.expTime) {
            params.expTime = params.expTime * 60 * 1000;
            exp.setTime(exp.getTime() + params.expTime);
            expires = ";expires=" + exp.toGMTString();
        }
        if (!params.domain) {
            params.domain = document.domain;
        }

        document.cookie = params.name + "="
            + params.value + "; path=/; domain=" + params.domain + ";" + expires;
    };

    /**
     * removeCookie
     */
    this.removeCookie = function (p) {
        var dp = {
            domain: "",
            name: "",
            path: "/"
        };
        if (typeof p == 'object') {
            this.extend(dp, p);
        } else if (typeof p == 'string') {
            dp.name = p;
        }
        if (!dp.domain) {
            dp.domain = document.domain;
        }


        that.log("移除cookie值,当前域为" + dp.domain + ",path为" + dp.path + ",key为" + dp.name);
        var exp = new Date("2000", "1", "1");
        var cval = this.getCookie(dp.name);
        if (cval != null) {
            that.log("成功移除key为" + dp.name + "的cookie值");
            document.cookie = dp.name + "=" + cval + ";domain=" + dp.domain + ";path=" + dp.path + ";expires=" + exp.toGMTString();
        } else {
            that.log("移除cookie值,不存在key为" + dp.name + "的cookie");
        }
    };

    /**
     * gotoUrl
     * @params url 目标地址
     * @params params 扩展参数
     */
    // base.gotoUrl("baidu.com", {callback: function(data){
    //     base.ajax.post({
    //         success:function(){
    //             if(true){

    //             }else{

    //             }
    //         }
    //     })
    //     console.log(data)
    // }})
    this.gotoUrl = function (url, params) {
        params = params || {};
        if (!url) {
            return false;
        }
        if (params.callback && base.isFunction(params.callback)) {
            params.callback(url)
            return false;
        }
        var checkAuthList = [
            // "/views/reinstate/reinstateIndex.html",

        ];
        // 判断是否需要做权限判断
        let checkFlag = checkAuthList.some(item => url.indexOf(item) > -1);
        if (checkFlag) {
            base.ajax.post({
                url: "",
                data: {
                },
                success: function (res) {
                    console.log(res)
                    if (true) {
                        window.location.href = url;
                    } else {
                        window.location.href = '';
                    }
                }
            })

            return false;
        }
        url = url || "";

        window.location.href = url;
    };

    this.gotoUrlByType = function (type) {
        //我的信息跳转
        if (!type) {
            return false;
        }
        let info = JSON.parse(base.getSessionStorage("baseInfo"));
        let hbqLinkId = sessionStorage.getItem('hbqLinkId');
        let linkid = sessionStorage.getItem('linkId');
        if(!(linkid == "" || linkid == null)){
            hbqLinkId = linkid
        }
        if ("syrbg" == type) {
            gotoSgsy(info, hbqLinkId);
        }else{
            //我的信息
            gotoMymessage(info, hbqLinkId);
        }
    };

    this.gotoUrlMyMessage = function () {
        let info = JSON.parse(base.getSessionStorage("baseInfo"));
        let hbqLinkId = sessionStorage.getItem('hbqLinkId');
        let linkid = sessionStorage.getItem('linkId');
        let sour = sessionStorage.getItem('sour');
        if(!(linkid == "" || linkid == null)){
            hbqLinkId = linkid
        }
        base.ajax.post({
            url: "/smart-policykeeper-service/pass/getTransferPageJumpUrl",
            data: {
                type: "xxbg",
                idnum: info.idnum,
                linkId: hbqLinkId,
                sour: sour,
            },
            success: function success(res) {
                base.gotoUrl(res.data)
            },
            error: function error(e) {
                alert('请求异常请稍后尝试。');
            },
        });
    }

    this.replaceUrl = function (url, params) {
        params = params || {};
        if (!url) {
            return false;
        }
        if (params.callback && base.isFunction(params.callback)) {
            params.callback(url)
            return false;
        }
        var checkAuthList = [
            // "/views/reinstate/reinstateIndex.html",

        ];
        // 判断是否需要做权限判断
        let checkFlag = checkAuthList.some(item => url.indexOf(item) > -1);
        if (checkFlag) {
            base.ajax.post({
                url: "",
                data: {
                },
                success: function (res) {
                    console.log(res)
                    if (true) {
                        window.location.replace(url);
                    } else {
                        window.location.replace('');
                    }
                }
            })

            return false;
        }
        url = url || "";

        window.location.replace(url);
    };

    /*保存人脸识别H5结果*/
    this.saveFaceResult = function (params){
        var request = {
            name    : params.name.replace(/\s+/g, ""),
            idnum   : params.idnum,
            bqtype  : params.bqtype,
            orderNo : sessionStorage.getItem("faceAIOrderNo"),
            startTime : sessionStorage.getItem("faceAIStartTime"),
            endTime : new Date().Format('yyyy-MM-dd hh:mm:ss'),
            reconResult : params.reconResult,
            channel : "1",
        };
        base.ajax.post({
            url: "/smart-policykeeper-service/aiCode/saveFaceResultToBqzt",
            data: request,
            success: function success(resp) {
            },
            error: function (resp) {
            }
        })
    }


    function gotoSgsy(info, hbqLinkId) {
        let policyNo = sessionStorage.getItem('sgsyPolNo')||'';
        sessionStorage.removeItem('sgsyPolNo');
        sessionStorage.removeItem("sgsyPolicyList")
        // if (sessionStorage.getItem('ispassSgsyxxbg') == '1') {
        //     if (policyNo) {
        //         base.gotoUrl(`${base.moduleUrl}/views/benefic0318/page/policyList.html?policyNo=${policyNo}&t=${new Date().getTime()}`)
        //     } else {
        //         base.gotoUrl(`${base.moduleUrl}/views/benefic0318/page/policyList.html?t=${new Date().getTime()}`)
        //     }
        // } else if (sessionStorage.getItem('ispassSgsy') == '1') {
        base.ajax.post({
            url: "/smart-policykeeper-service/pass/getTransferPageJumpUrl",
            data: {
                type: "syrbg",
                idnum: info.idnum,
                linkId: hbqLinkId,
                sour: "wx",
                policyNo: policyNo
            },
            success: function success(res) {
                base.gotoUrl(res.data)
            },
            error: function error(e) {
                alert('请求异常请稍后尝试。');
            },
        });
        // } else {
        //     if (policyNo) {
        //         base.gotoUrl(`${base.moduleUrl}/views/benefic/page/policyList.html?policyNo=${policyNo}&t=${new Date().getTime()}`)
        //     } else {
        //         base.gotoUrl(`${base.moduleUrl}/views/benefic/page/policyList.html?t=${new Date().getTime()}`)
        //     }
        // }
    }

    function gotoMymessage(info, hbqLinkId) {
        // if (sessionStorage.getItem('elderlyChannel') === "1" &&
        //     sessionStorage.getItem('elderlyMyinfoSwitch') === "1") { //老人版
        //     base.gotoUrl(`${base.moduleUrl}/views-elderly/cusInfo/page/mymessage.html`)
        // }
        // if (sessionStorage.getItem('elderlyChannel') !== "1") {
        //  if (sessionStorage.getItem('isMessNew') === '1') {
        base.ajax.post({
            url: "/smart-policykeeper-service/pass/getTransferPageJumpUrl",
            data: {
                type: "xxbg",
                idnum: info.idnum,
                linkId: hbqLinkId,
                sour: "wx",
            },
            success: function success(res) {
                base.gotoUrl(res.data)
            },
            error: function error(e) {
                alert('请求异常请稍后尝试。');
            },
        });
        // }
        // else {
        //     // return `${base.moduleUrl}/views/cusInfo/page/mymessage.html`
        //     base.gotoUrl(`${base.moduleUrl}/views/newCusInfo/page/mymessage.html`)//该新版测试环境调试
        // }
        // }
    }

    this.getModno = function (bqtype, callBack) {
        //获取批单号
        var sour = sessionStorage.getItem('sour');
        var flag1= '1';
        if (sour == 'hbq') {
            flag1 = '6';
        } else if (sour == 'app') {
            flag1 = '2';
        } else if (sour == 'pudev') {
            flag1 = '9';
        }
        base.ajax.post({
            url: '/smart-policykeeper-service/common/getModno',
            data: {
                "flag": flag1,
                "bqtype": bqtype,
                "sessionId": sessionStorage.sessionId,
                "accXT": '00004',//接入系统 00001-APP 00002-微信 00003-太享福 00004-保单管家
            },
            success: function (res) {
                if(res.resCode == "0000"){
                    var modno=res.result;//批单号
                    sessionStorage.modno = modno;
                    callBack();
                }else{
                    alert('获取批单号失败');
                }
            },
            error: function () {
                alert('获取批单号失败');
            }
        });
    }


    // 发送统计数据
    this.sendStatisticsData = function (token, businessType, operResult, code, message) {
        // 是否属于本地开发环境
        var isAuto = window.location.href.indexOf(window.location.protocol + "//localhost") == -1 &&
            window.location.host != "" &&
            (!/^file/.test(window.location.href));

        var urlRoot = function () {
            var durl = "https://onesit.cpic.com.cn/Proxy/";
            if (isAuto) {
                durl = window.location.protocol + "//" + window.location.host + "/Proxy/";
            }
            return durl;
        }();

        //报表
        var urlRootForm = function () {
            return urlRoot;
        }();
        var byForm = (u) => urlRootForm + u

        var actionConf = {
            saveCustomer: {
                saveCustomerOperateDetail: byForm("customerOperateReportApi/saveCustomerOperateDetail"),//报表提交
            },
        }


        var mydata = function () {
            console.log(that)
            var clien = that.operatingSystem.container
            var clientType = "pc";
            if (clien == "weixin") {
                clientType = "wechat"
            } else if (document.hasOwnProperty("ontouchstart")) {
                clientType = "touch"
            }
            var _data = {
                "businessType": businessType,//业务类型
                "operResult": operResult,//操作结果
                "operCode": code,//操作失败编码	
                "operMessage": message,//操作失败信息
                "clientType": clientType, //触点类型  pc(电脑),touch(触屏),wechat(微信),app(APP)
            }
            return _data;
        }();


        Vue.$ajax.get({
            url: actionConf.saveCustomer.saveCustomerOperateDetail,
            options: {
                params: mydata
            }
        });
    };

    //  更换title值
    this.changeTitle = function (item) {
        if (item) {
            document.getElementsByTagName('title')[0].innerHTML = item;
        }
    }

    var readyFnList = [];

    // unshift 是否追加到第一位
    this.ready = function (fn, unshift) {
        if (readyState == "wait" && fn) {
            if (unshift === true) {
                readyFnList.unshift(fn);
            } else {
                readyFnList.push(fn);
            }
        } else if (readyState == "ready") {
            for (var i; readyFnList.length;) {
                readyFnList.shift()();
            }
            fn && fn();
        }
    };


    /**
     * initRequireJs
     */
    var initRequireJs = function () {

        this.requireComplete = true;

        require.config({
            urlArgs: "_t=" + _time,
            baseUrl: this.moduleBaseUrl,
            paths: {
                jquery: "./core/jquery.min",
                crypto: './core/crypto-js/crypto-js',
                cslsharer: './base/js/csl-sharer',
                bdgjcrypto: './base/component/common/bdgjcrypto',
                iscroll: './core/iscroll',
                jmpopups: './core/jquery.jmpopups-0.5.1',
                require_css: "./core/require_css",
                require_text: "./core/require_text",
                jweixin: this.environment == 'local' ? './core/weixin' : "https://res.wx.qq.com/open/js/jweixin-1.6.0",
                // jweixin: "https://res.wx.qq.com/open/js/jweixin-1.6.0",
                weixinShare: './base/component/common/weixinShare',
                cropper: './base/component/ui/cropper3',
                swipper: './base/component/ui/swiper-3.4.2.min',
                pageAddress: "./config/pageAddress",//所有跳转页面绝对地址
                actionConf: "./config/actionConf",//所有跳转页面绝对地址
                ajax: "./base/component/common/ajax",
                util: "./base/component/common/util",
                model: "./base/component/ui/model",
                ui: "./base/component/ui/ui",
                valiformdata: './base/component/common/valiformdata',
                sigin: './base/component/common/esign', // 签名
                qrcode: './core/qrcode.min', //生成二维码
                mobiscroll: './core/mobiscroll.custom-2.6.2.min', //日历插件
                enumChange: "./base/component/common/enumChange",
                vCodeApi: "./base/component/common/vcode",//短信验证码
                vCodePop: "./base/component/ui/vcodeElderly",//老人版短信验证码校验弹框
                areaSheet: "./views-elderly/cusInfo/js/areaSheet",
                mobiscroll3: "./views/cusInfo/js/mobiscroll.custom-3.0.0.min",
                antiMoney: "./base/component/common/antiMoney",//反洗钱
                antiMoney2: "./base/component/common/antiMoney2",//反洗钱2
                autographSheet:"./views-elderly/cusInfo/js/autographSheet",
                // dateSheet: "./views-elderly/cusInfo/js/dateSheet",
                elderlyApply: "./views-elderly/cusInfo/js/apply",
                newcusApply: "./views/newCusInfo/js/apply",
                authBankUtil: "./views-elderly/jffs/js/authBankUtil",//银行授权校验
            },
            //超时时间
            waitSeconds: 60,
            map: {
                '*': {
                    'css': 'require_css',
                    'text': 'require_text'
                }
            },
            shim: {
                // 对应组件的css引入
                // VeeValidate: ["css!./base/component/plugins/vee-validate.css", "./base/component/plugins/vee-validate"],
                'model': ['css!./base/component/ui/css/model.css'],
                "cropper": ['css!./base/component/ui/css/cropper.css'],
                "swipper": ['css!./base/component/ui/css/swiper-3.4.2.min.css']
            }
        });

    }.bind(this),

        /**
         * 添加需要等待执行的模块
         * @params modules string 模块名称
         * @params fn function 回调函数
         * @params cordova boole 是否cordova插件
         */
        addPending = function (modules, fn, cordova) {

            pendingModule.push({
                modules: modules,
                fn: fn,
                cordova: cordova
            });

        }.bind(this),

        /**
         * 执行模块
         * @params modules string 模块名称
         * @params fn function 回调函数
         * @params cordova boole 是否cordova插件
         */
        runRequire = function (modules, fn, cordova) {

            if (!this.requireComplete) {
                addPending(modules, fn, cordova);
            } else {
                //如果当前调用cordova插件方法且cordova未准备完成
                if (cordova && !this.cordovaComplete) {

                    if (this.isRunApp) {
                        if (this.cordovaComplete) {
                            require(this.isArray(modules) ? modules : [modules], fn);
                        } else {
                            addPending(modules, fn, cordova);
                        }
                    }

                    return;
                }
                require(this.isArray(modules) ? modules : [modules], fn);
            }

        }.bind(this),

        /**
         * 运行所有等待执行的模块
         */
        runAllPending = function () {

            pendingModule.forEach(function (m) {
                runRequire(m.modules, m.fn, m.cordova);
            });

            pendingModule = [];

        }.bind(this),

        readyMain = function () {

            var _count = 0;

            // perModule = ['jquery', 'iscroll', 'jmpopups', 'ui','mobiscroll', ...perModule];
            if(that.environment == 'local') {
                perModule = ['jquery', 'iscroll', 'jmpopups', 'ui','mobiscroll', ...perModule];
            }else{
                perModule = ['jquery', 'iscroll', 'jmpopups', 'ui', "weixinShare",'mobiscroll', ...perModule];               
            }
            

            var _callee = function () {
                runRequire(perModule[_count++], function (o) {
                    if (_count >= perModule.length) {

                        // 每个页面调用一次
                        that.ready(function () {

                        }, true); // 追加到待执行列表的第一位

                        readyState = "ready";

                        that.win = {
                            width: $(window).width(),
                            height: $(window).height()
                        };

                        that.ready();

                        that.eventLog();
                        if (readyMainSrc) {
                            that.loadJsCssFile({
                                filename: readyMainSrc
                            });
                        }
                    } else {
                        _callee();
                    }
                });
            };
            _callee();


        }.bind(this),

        /**
         * initMethod
         * @params categories string 当前对象下一级命名空间名城 例如: saic.saicMethod
         * @params mets array 指定命名空间下所有方法名
         */
        initMethod = function (categories, mets) {

            this[categories] = function () {

                //方法集合
                var exports = {};

                mets.forEach(function (f) {

                    //方法名称
                    var fn = typeof f == 'string' ? f : f.fn,

                        //是否cordova插件
                        isCordova = f.cordova === true;

                    exports[fn] = function () {
                        var params = [].slice.call(arguments);

                        if (isCordova) {
                            params.unshift(fn);
                        }

                        runRequire(categories, function (m) {
                            if (that.isFunction(m)) {
                                //如果返回的就是function对象,直接执行
                                m.apply(that, params);
                            }
                            else if (params.length == 1 && that.isFunction(params[0])) {
                                //判断是否自己处理返回模块
                                params[0](m[fn]);
                            } else {
                                m[fn].apply(that, params);
                            }

                        }, isCordova);

                    };

                });

                return exports;
            }();

        }.bind(this);

    /**
     * 预加载模块
     * @params names string or array 预先加载指定模块
     */
    this.preLoadModule = function (names) {
        runRequire(this.isArray(names) ? names : [names], null);
    };

    function _runModule(mname, fn, params, isapply) {
        runRequire(mname, function (m) {
            if (isapply !== false) {
                m[fn].apply(that, params);
            } else {
                m[fn].apply(m, params);
            }
        }, false);
    }


    /**
     * init Ui Module
     */
    (function () {

        function _ui(fn, params) {
            runRequire("model", function (m) {
                m[fn].call(that, params);
            }, false);
        }

        var uis = ["alert", "confirm", "toast", "toast5s"];

        uis.forEach(function (v) {
            that[v] = function (params) {
                _ui(v, params);
            }
        });
        that.loading = {
            open: function (params) {
                _ui("loading", "open");
            },
            close: function (params) {
                _ui("loading", "close");
            }
        }
    })();

    /**
     * ajax
     */
    initMethod("ajax", [
        "post"
        , "get"
        , "jsonp"
        , "promise"
    ]);

    /**
    * crypto
    */
    // initMethod("bdgjcrypto", [
    //     "Decrypt"
    //     , "Encrypt"
    // ]);

    // this.bdgjcrypto = function () {
    //     var exports = {};
    //     ["Decrypt", "Encrypt"].forEach(function (v) {
    //         exports[v] = function () {
    //             _runModule("bdgjcrypto", v, [].slice.call(arguments))
    //         }
    //     });
    //     return exports;
    // }();

    this.weixinShare = {
        //好友
        shareMessageToFriend: function (params) {
            // if (base.operatingSystem.container == "weixin") {
            runRequire("weixinShare", function (m) {
                m.shareMessageToFriend(params);
            }, false);
            // }
        },
        //朋友圈
        shareTimeline: function (params) {
            // if (base.operatingSystem.container == "weixin") {
            runRequire("weixinShare", function (m) {
                m.shareTimeline(params);
            }, false);
            // }
        },
        chooseImage: function (params) {
            // if (base.operatingSystem.container == "weixin") {
            runRequire("weixinShare", function (m) {
                m.chooseImage(params);
            }, false);
            // }
        },
        takeCamera: function (params) {
            // if (base.operatingSystem.container == "weixin") {
            runRequire("weixinShare", function (m) {
                m.takeCamera(params);
            }, false);
            // }
        },
    };

    this.getParam = function(name) {
        // 如果链接没有参数，或者链接中不存在我们要获取的参数，直接返回空
        if (location.href.indexOf("?") == -1 || location.href.indexOf(name + '=') == -1) {
            return '';
        }
        // 获取链接中参数部分
        var queryString = location.href.substring(location.href.indexOf("?") + 1);
        try {
            queryString = decodeURI(queryString);
        } catch (e) {
            console.log(e);
        }
        // 分离参数对 ?key=value&key2=value2
        var parameters = queryString.split("&");
        var pos, paraName, paraValue;
        for (var i = 0; i < parameters.length; i++) {
            // 获取等号位置
            pos = parameters[i].indexOf('=');
            if (pos == -1) {
                continue;
            }
            // 获取name 和 value
            paraName = parameters[i].substring(0, pos);
            paraValue = parameters[i].substring(pos + 1);
            // 如果查询的name等于当前name，就返回当前值，同时，将链接中的+号还原成空格
            if (paraName == name) {
                // return unescape(paraValue.replace(/\+/g, " "));
                return paraValue;
            }
        }
        return '';
    }

}).call(base);


/*******原型方法添加*******/

/**
 * 添加或者替换
 * @params [0]  字符串或者json数组对象 [ { k:v } ]
 * @params [1]  当参数0为以字符串作为key时此参数为value
 * @return String
 */
String.prototype.toggleUrlParams = function (k, v) {
    var str = this.toString(),
        reg1 = new RegExp("\\?" + k + "\=.*?\&", "g"),
        reg2 = new RegExp("\&" + k + "\=.*?\&", "g"),
        reg3 = new RegExp("\\?" + k + "\=.*$", "g"),
        reg4 = new RegExp("\&" + k + "\=.*$", "g"),
        m1 = "";

    var _olstr = str;

    //删除锚点数据
    if (/\#.*?/.test(str)) {
        str = str.substring(0, str.indexOf("#"));
        m1 = _olstr.substring(_olstr.indexOf("#"));
    }

    str = str.replace(reg1, "?")
        .replace(reg2, "&")
        .replace(reg3, "")
        .replace(reg4, "");

    return str += (/\?/.test(str) ? "&" : "?") + (k + "=" + v) + m1;
};

/**
 * 得到地址栏参数
 * @param name 参数名称
 * @param urls 从指定的urls获取参数
 * @returns string
 */
String.prototype.getQueryString = function (name, urls) {
    urls = urls || window.location.href;
    if (this) {
        urls = this;
    }

    //删除锚点数据
    if (/\#.*?\&/.test(urls)) {
        urls = urls.substring(0, urls.lastIndexOf("#"));
    }

    if (urls && urls.indexOf("?") > -1) { urls = urls.substring(urls.indexOf("?") + 1); }
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = urls ? urls.match(reg) : window.location.search.substr(1).match(reg);
    if (r != null && r[2] != "") {
        var ms = r[2].match(/(\<)|(\>)|(%3C)|(%3E)/g);
        if (ms && ms.length >= 4) {
            //如果检测到有2对及以上开始和结束尖括号
            r[2] = r[2].replace(/(\<)|(%3C)/g, "");
        }
        return r[2];
        // return  unescape(r[2]);
    }
    return null;
};

/**
 * 
 * 添加日期原型方法
 */
String.prototype.FormatDate = function (fmt) {
    var date = this;
    var arr = date.match(/(\d+)/g)
    var _y = arr[0] | 0,
        _M = (arr[1] | 1) - 1,
        _d = arr[2] | 1,
        _h = arr[3] | 0,
        _m = arr[4] | 0,
        _s = arr[5] | 0;

    return new Date(_y, _M, _d, _h, _m, _s).Format(fmt);
};

/**
 * 格式化金钱
 * @places  保留几位小数
 * @symbol  金钱单位
 * @thousand 千位分割符 默认为,
 * @decimal 
 * @return String
 */
Number.prototype.formatMoney = function (places, symbol, thousand, decimal) {
    places = !isNaN(places = Math.abs(places)) ? places : 2;
    symbol = symbol !== undefined ? symbol : "￥";
    thousand = thousand || ",";
    decimal = decimal || ".";
    var number = this,
        negative = number < 0 ? "-" : "",
        i = parseInt(number = Math.abs(+number || 0).toFixed(places), 10) + "",
        j = (j = i.length) > 3 ? j % 3 : 0;
    return symbol + negative + (j ? i.substr(0, j) + thousand : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousand) + (places ? decimal + Math.abs(number - i).toFixed(places).slice(2) : "");
};
Number.prototype.toHanziNum = function () {

    var chnNumChar = ["零", "一", "二", "三", "四", "五", "六", "七", "八", "九"];
    var chnUnitSection = ["", "万", "亿", "万亿", "亿亿"];
    var chnUnitChar = ["", "十", "百", "千"];

    return (function (section) {
        var strIns = '', chnStr = '';
        var unitPos = 0;
        var zero = true;
        while (section > 0) {
            var v = section % 10;
            if (v === 0) {
                if (!zero) {
                    zero = true;
                    chnStr = chnNumChar[v] + chnStr;
                }
            } else {
                zero = false;
                strIns = chnNumChar[v];
                strIns += chnUnitChar[unitPos];
                chnStr = strIns + chnStr;
            }
            unitPos++;
            section = Math.floor(section / 10);
        }
        return chnStr;
    })(this)
};
Date.prototype.Format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
};
Date.prototype.addHours = function (h) {
    this.setHours(this.getHours() + h);
    return this;
};
Date.prototype.addDays = function (d) {
    this.setDate(this.getDate() + d);
    return this;
};
Date.prototype.addWeeks = function (w) {
    this.addDays(w * 7);
    return this;
};
Date.prototype.addMonths = function (m) {
    var d = this.getDate();
    this.setMonth(this.getMonth() + m);
    if (this.getDate() < d)
        this.setDate(0);
    return this;
};
Date.prototype.addYears = function (y) {
    var m = this.getMonth();
    this.setFullYear(this.getFullYear() + y);
    if (m < this.getMonth()) {
        this.setDate(0);
    }
    return this;
};
/*interval ：D表示查询精确到天数的之差
 interval ：H表示查询精确到小时之差
 interval ：M表示查询精确到分钟之差
 interval ：S表示查询精确到秒之差
 interval ：T表示查询精确到毫秒之差*/
Date.prototype.dateDiff = function (interval, date2) {
    var objInterval = { 'D': 1000 * 60 * 60 * 24, 'H': 1000 * 60 * 60, 'M': 1000 * 60, 'S': 1000, 'T': 1 };
    interval = interval.toUpperCase();
    var date2Convert = new Date(date2.replace(/-/g, '/'));
    var thisDateFormat = "yyyy/MM/dd hh:mm:sss";
    switch (interval) {
        case "D":
            thisDateFormat = "yyyy/MM/dd 00:00:000";
            break;
        case "H":
            thisDateFormat = "yyyy/MM/dd hh:00:000";
            break;
        case "M":
            thisDateFormat = "yyyy/MM/dd hh:mm:000";
            break;
        case "S":
            break;
        case "T":
            break;
    }
    var dt1 = Date.parse(this.Format(thisDateFormat));
    var dt2 = Date.parse(date2Convert.Format(thisDateFormat));
    try {
        return Math.round((dt2 - dt1) / objInterval[interval]);
    } catch (e) {

    }
}
